#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <set>
#include <map>
using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        int n = 0;
        ListNode* p = head, * last;
        while (p != NULL)
        {
            n++;
            last = p;
            p = p->next;
        }
        if (!n)return head;
        k %= n;
        n = n - k - 1;
        p = head;
        while (n--)p = p->next;
        last->next = head;
        head = p->next;
        p->next = NULL;
        return head;

    }
};